package com.cofi.vueelementadminserver.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author xyh
 * @date 2025-01-06
 * @description
 */
@Component
public class SplitLoginFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //1.判断是否为post请求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("请使用指定方式请求登录: " + request.getMethod());
        }
        //2.判断是否为json参数
        if(request.getContentType().toLowerCase().contains(MediaType.APPLICATION_JSON_VALUE)){
            //3.从json中获取用户输入数据
            try {
                Map<String,String> userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                String username = userInfo.getOrDefault(super.getUsernameParameter(),"username");
                String password = userInfo.getOrDefault(super.getPasswordParameter(),"password");
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                setDetails(request, authRequest);
                Authentication authenticate = this.getAuthenticationManager().authenticate(authRequest);
                return authenticate;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return super.attemptAuthentication(request, response);
    }
}
